package com.lanou3g.web;

import com.lanou3g.bean.User;
import com.lanou3g.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/login_page")
    public String toLogin() {

//        return "login";    // /WEB-INF/login.jsp(地址栏：/user/login_page)
//        return "forward:login"; // /user/login(地址栏：/user/login_page)
//        return "redirect:login";  // /user/login(地址栏：/user/login)
//        return "redirect:/login";  // /user/login(地址栏：/user/login)
        return "forward:/login.jsp"; // /login.jsp(地址栏：/user/login_page)
//        return "redirect:/login.jsp";  // /login.jsp(地址栏：login.jsp)
    }

    @RequestMapping("/login")
    public String login(User user, String rem, HttpServletResponse resp, Model model) {

        // 获取用户输入的用户名
        String inputUsername = user.getUsername();
        String inputPassword = user.getPassword();

        User user1 = userMapper.selectByUserName(inputUsername);
        if(user1 == null) {
            // 账户不存在
            model.addAttribute("msg", "账户不存在，请先注册！");
            return "forward:/login.jsp";
        }
        if(!user1.getPassword().equals(inputPassword)) {
            // 用户名或密码错误
            model.addAttribute("msg", "用户名或密码错误！");
            return "forward:/login.jsp";
        }
        if("on".equals(rem)) {
            // 记住密码功能
            Cookie userC = new Cookie("user", inputUsername);
            Cookie pwdC = new Cookie("pwd", inputPassword);
            userC.setPath("/");
            pwdC.setPath("/");
            resp.addCookie(userC);
            resp.addCookie(pwdC);
        }

        return "redirect:showList";
    }

    @RequestMapping("/showList")
    public String login(Model model) {
        List<User> users = userMapper.selectAll();
        model.addAttribute("userList", users);
        return "admin/list";
    }
}
